package com.zhuizikejithreeig.cn.threeigkeji;


import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.ViewDragHelper;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.zhuizikejithreeig.cn.adapter.MyPagerAdapter;
import com.zhuizikejithreeig.cn.been.NewMainBeen;
import com.zhuizikejithreeig.cn.been.UpDataBeen;
import com.zhuizikejithreeig.cn.braodcast.NetBroadcastReceiver;
import com.zhuizikejithreeig.cn.braodcast.NetUtil;
import com.zhuizikejithreeig.cn.braodcast.PrensentView;
import com.zhuizikejithreeig.cn.content.ContectUtils;
import com.zhuizikejithreeig.cn.content.UriContect;
import com.zhuizikejithreeig.cn.fragment.SimpleCardFragment;
import com.zhuizikejithreeig.cn.threeigkeji.loginfo.BasicInfoActivity;
import com.zhuizikejithreeig.cn.threeigkeji.loginfo.LoginActivity;
import com.zhuizikejithreeig.cn.threeigkeji.loginfo.SettingActivity;
import com.zhuizikejithreeig.cn.threeigkeji.mianinfo.EmailActivity;
import com.zhuizikejithreeig.cn.threeigkeji.mianinfo.EquipFixActivity;
import com.zhuizikejithreeig.cn.threeigkeji.mianinfo.WalletActivity;
import com.zhuizikejithreeig.cn.utils.AppManager;
import com.zhuizikejithreeig.cn.utils.GsonUtil;
import com.zhuizikejithreeig.cn.utils.ToastMake;
import com.zhuizikejithreeig.cn.utils.Utils;
import com.zhuizikejithreeig.cn.weigit.NoScrollViewPager;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.onekeyshare.OnekeyShare;
import de.hdodenhof.circleimageview.CircleImageView;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;
import okhttp3.Call;
import okhttp3.MediaType;

public class MainActivity extends BasicActivity implements View.OnClickListener, PrensentView {
    private DrawerLayout mDrawer;
    private LinearLayout mMoney;
    private LinearLayout mCustomer;
    private LinearLayout mSetting;
    private LinearLayout mFix;
    private LinearLayout mControl;
    private NoScrollViewPager mViewPager;
    private TextView mShare;
    private boolean hasPermission = false;
    private static final int READSDK = 200;
    private long exitTime = 0;
    private NewMainBeen mBeen;
    private RelativeLayout mFirst;
    private RelativeLayout mSecond;
    private RelativeLayout mThird;
    private RelativeLayout mFour;
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private MyPagerAdapter mAdapter;
    private String mUserId;
    private List<Integer> postion = new ArrayList<>();
    private boolean haveNet = false;
    private ImageView mFirstImage;
    private ImageView mSecondImage;
    private ImageView mThirdImage;
    private ImageView mFourImage;
    private TextView mFirstText;
    private TextView mSecondText;
    private TextView mThirdText;
    private TextView mFourText;
    private int curritemPostion = 0;
    private TextView netbroke;
    /**
     * 网络类型
     */
    private int netMobile;
    //TODO:监听网络时时刻刻的变化

    private CircleImageView mCircleImageView;
    private TextView mNackName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_main);
        showBody();
        findViewById(R.id.user).setOnClickListener(this);
        findViewById(R.id.message).setOnClickListener(this);
        //初始化加载头像图片
        mCircleImageView = (CircleImageView) findViewById(R.id.circleimage);
        mNackName = (TextView) findViewById(R.id.naeckname);
        //初始化头像


        mViewPager = (NoScrollViewPager) findViewById(R.id.viewpager);
        mShare = (TextView) findViewById(R.id.share);
        mDrawer = (DrawerLayout) findViewById(R.id.drawer);
        mViewPager.setNoScroll(true);

        //侧滑菜单
        mMoney = (LinearLayout) findViewById(R.id.money);
        mCustomer = (LinearLayout) findViewById(R.id.customer);
        mSetting = (LinearLayout) findViewById(R.id.setting);
        mFix = (LinearLayout) findViewById(R.id.fix);
        mControl = (LinearLayout) findViewById(R.id.control);

        mMoney.setOnClickListener(this);
        mCustomer.setOnClickListener(this);
        mSetting.setOnClickListener(this);
        mFix.setOnClickListener(this);
        mShare.setOnClickListener(this);
        mControl.setOnClickListener(this);

        //默认按钮状态
        mFirst = (RelativeLayout) findViewById(R.id.first);
        mSecond = (RelativeLayout) findViewById(R.id.second);
        mThird = (RelativeLayout) findViewById(R.id.third);
        mFour = (RelativeLayout) findViewById(R.id.four);
        netbroke = (TextView) findViewById(R.id.netbroke);


        mFirst.setOnClickListener(this);
        mSecond.setOnClickListener(this);
        mThird.setOnClickListener(this);
        mFour.setOnClickListener(this);

        mFirstImage = (ImageView) findViewById(R.id.first_iamge);
        mSecondImage = (ImageView) findViewById(R.id.second_iamge);
        mThirdImage = (ImageView) findViewById(R.id.third_iamge);
        mFourImage = (ImageView) findViewById(R.id.four_image);


        mFirstText = (TextView) findViewById(R.id.first_text);
        mSecondText = (TextView) findViewById(R.id.second_text);
        mThirdText = (TextView) findViewById(R.id.third_text);
        mFourText = (TextView) findViewById(R.id.four_text);
        //初始化默认

        mFirstText.setTextColor(getResources().getColor(R.color.textColor3));
        mFirstImage.setVisibility(View.VISIBLE);
        //TODO:解决全屏滑动而不能出现侧滑
        //        setDrawerLeftEdgeSize(MainActivity.this, mDrawer, 1);

        hasReadPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);


        //有无网状态
        if (isConnected()) {
            netbroke.setVisibility(View.INVISIBLE);
            mViewPager.setVisibility(View.VISIBLE);
            UpdataApk();
        } else {
            ToastMake.showToast(getResources().getString(R.string.string57));
            //TODO:原则上应该打开Login界面
            haveNet = true;
            netbroke.setVisibility(View.VISIBLE);
            mViewPager.setVisibility(View.INVISIBLE);
        }
//        CompontApplayCation.postion = (curritemPostion + 1)+"";
//        if (!CompontApplayCation.postion.equals("1")){
            curritemPostion = Integer.parseInt(CompontApplayCation.postion) - 1;
//        }
        //指定滚动到第一个界面
        mViewPager.setCurrentItem(curritemPostion, true);


        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                curritemPostion = position;
                CompontApplayCation.postion = (curritemPostion + 1)+"";
                if (position == 0) {
                    mFirstText.setTextColor(getResources().getColor(R.color.textColor3));
                    mSecondText.setTextColor(getResources().getColor(R.color.textColor4));
                    mThirdText.setTextColor(getResources().getColor(R.color.textColor4));
                    mFourText.setTextColor(getResources().getColor(R.color.textColor4));
                    mFirstImage.setVisibility(View.VISIBLE);
                    mSecondImage.setVisibility(View.INVISIBLE);
                    mThirdImage.setVisibility(View.INVISIBLE);
                    mFourImage.setVisibility(View.INVISIBLE);
                } else if (position == 1) {
                    mFirstText.setTextColor(getResources().getColor(R.color.textColor4));
                    mSecondText.setTextColor(getResources().getColor(R.color.textColor3));
                    mThirdText.setTextColor(getResources().getColor(R.color.textColor4));
                    mFourText.setTextColor(getResources().getColor(R.color.textColor4));
                    mFirstImage.setVisibility(View.INVISIBLE);
                    mSecondImage.setVisibility(View.VISIBLE);
                    mThirdImage.setVisibility(View.INVISIBLE);
                    mFourImage.setVisibility(View.INVISIBLE);

                } else if (position == 2) {

                    mFirstText.setTextColor(getResources().getColor(R.color.textColor4));
                    mSecondText.setTextColor(getResources().getColor(R.color.textColor4));
                    mThirdText.setTextColor(getResources().getColor(R.color.textColor3));
                    mFourText.setTextColor(getResources().getColor(R.color.textColor4));
                    mFirstImage.setVisibility(View.INVISIBLE);
                    mSecondImage.setVisibility(View.INVISIBLE);
                    mThirdImage.setVisibility(View.VISIBLE);
                    mFourImage.setVisibility(View.INVISIBLE);
                } else if (position == 3) {
                    mFirstText.setTextColor(getResources().getColor(R.color.textColor4));
                    mSecondText.setTextColor(getResources().getColor(R.color.textColor4));
                    mThirdText.setTextColor(getResources().getColor(R.color.textColor4));
                    mFourText.setTextColor(getResources().getColor(R.color.textColor3));
                    mFirstImage.setVisibility(View.INVISIBLE);
                    mSecondImage.setVisibility(View.INVISIBLE);
                    mThirdImage.setVisibility(View.INVISIBLE);
                    mFourImage.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (CompontApplayCation.formLgin) {
            chice();
            CompontApplayCation.formLgin = false;
        }

//        if (mDrawer.isDrawerOpen(GravityCompat.START)) {
//            mDrawer.closeDrawer(GravityCompat.START);
//        }

        //开始注册广播
        if (netWorkStateReceiver == null) {
            netWorkStateReceiver = new NetBroadcastReceiver(MainActivity.this);
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkStateReceiver, filter);


        Glide.with(MainActivity.this).
                load(Utils.getString(ContectUtils.IMAGEICONURI)).
                asBitmap().
                placeholder(R.mipmap.applogo).
                into(mCircleImageView);
        mNackName.setText(Utils.getString(ContectUtils.NICKNAME));
    }

    private void chice() {
        String phone = Utils.getString(ContectUtils.PHONESAVE);
        String status = Utils.getString(ContectUtils.STATUS);

        if (TextUtils.isEmpty(phone)) {
            phone = CompontApplayCation.phone;
        }

//        mFragments.clear();
        if (TextUtils.isEmpty(status)) {
            haveNoBundingDta();
            if (!CompontApplayCation.mianToLogin) {
                //为了防止回退的时候
                CompontApplayCation.mianToLogin = true;
//                skipOtherActivity(LoginActivity.class, false);
            }


            return;
        } else {

            if (TextUtils.equals("2", status)) {
                //TODO:如果没有扫描完。进入扫描界面
                Intent intent = new Intent(MainActivity.this, BasicInfoActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
                finish();
            } else if (TextUtils.equals("3", status)) {
                //skipOtherActivity(BundingSetActivity.class, false);
                newHaveRegistData(phone);
            } else if (TextUtils.equals("4", status)) {
                newHaveRegistData(phone);
            } else {
                skipOtherActivity(LoginActivity.class, false);
            }
        }
    }

    private void newHaveRegistData(String phone) {
        HashMap<String, String> map = new HashMap<>();
        map.put("phone", phone);
        String json = GsonUtil.parseMapToJson(map);
        showProgrees("加载中请稍等....");
        OkHttpUtils
                .postString()
                .url(UriContect.GETUSERBINDS)
                .content(json)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastMake.showToast(getResources().getString(R.string.string57));
                        hideProgree();
                        //原则上进入登录界面
//                        Utils.runOnUIThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                skipOtherActivity(LoginActivity.class, true);
//                            }
//                        });
                        haveNoBundingDta();

                        return;
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        hideProgree();
                        mBeen = GsonUtil.parseJsonToBean(response, NewMainBeen.class);
                        if (mBeen == null) {
                            //TODO:只要出现错误原则上在登录一次
//                            skipOtherActivity(LoginActivity.class, false);
                            ToastMake.showToast(getResources().getString(R.string.string57));
                            haveNoBundingDta();
                            return;
                        }
                        if (!TextUtils.equals(mBeen.getError_code(), "0")) {
                            ToastMake.showToast(mBeen.getMsg());
                            //TODO:只要出现错误原则上在登录一次
                            // skipOtherActivity(LoginActivity.class,true);

                            haveNoBundingDta();
                            return;
                        } else {
                            //TODO:获取二维码图片
                            showMac(mBeen.getData());
                            //                            //显示消息个数
                            //                            String state = mBeen.getState();
                            //                            if (TextUtils.equals(state, "1")) {
                            //                                setRightShow(1, R.mipmap.message);
                            //                            } else {
                            //                                setRightShow(1, R.mipmap.message_red);
                            //                            }
                            //                            //显示加载照片
                            //                            //设置viewPager关联,并且解决索引越界的问题
                            //                            if (mBeen.getData() != null) {
                            //                                mSize = mBeen.getData().size();
                            //                            } else {
                            //                                mSize = 0;
                            //                            }


                        }

                    }
                });
    }

    private void haveNoBundingDta() {
        mFragments.clear();
        for (int i = 0; i < 4; i++) {
            mFragments.add(SimpleCardFragment.getInstance((i) + "", "", ""));
        }
        mAdapter = new MyPagerAdapter(getSupportFragmentManager(), mFragments);
        mViewPager.setAdapter(mAdapter);
        //自动滚动到指定界面
        mViewPager.setCurrentItem(curritemPostion, true);
        CompontApplayCation.postion = (curritemPostion + 1)+"";
    }


    private void showMac(NewMainBeen.DataBean data) {
        List<NewMainBeen.DataBean.DriverBindListBean> mSize = data.getDriverBindList();
        //TODO:有二维码图片的集合
        postion.clear();
        List<String> uri = new ArrayList<>();
        for (int i = 0; i < mSize.size(); i++) {
            postion.add(Integer.parseInt(mSize.get(i).getPosition()));
            uri.add(mSize.get(i).getQrcodeUrl());
        }
        List<NewMainBeen.DataBean.MassageBean> massage = data.getMassage();
        if (massage!=null&&massage.size()!=0){
            CompontApplayCation.mBeenMessage = massage;
        }
        mFragments.clear();
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < postion.size(); j++) {
                //TODO:座椅的位置是从1开始算起的,而不是哦从零开始的
                if (i + 1 == postion.get(j)) {
                    mFragments.add(SimpleCardFragment.getInstance((i) + "", uri.get(j), ""));
                }
            }
            //TODO:为了防止重复不断的加入,要做限制
            if (mFragments.size() <= i) {
                mFragments.add(SimpleCardFragment.getInstance((i) + "", "", ""));
            }
        }
        Utils.runOnUIThread(new Runnable() {
            @Override
            public void run() {
                mAdapter = new MyPagerAdapter(getSupportFragmentManager(), mFragments);
                mViewPager.setAdapter(mAdapter);
                mAdapter.notifyDataSetChanged();
                mViewPager.setCurrentItem(curritemPostion, true);
                CompontApplayCation.postion = (curritemPostion + 1)+"";
            }
        });
    }

    private void hasReadPermission(String permission) {
        PermissionGen.with(MainActivity.this)
                .addRequestCode(READSDK)
                .permissions(
                        permission
                )
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @PermissionSuccess(requestCode = READSDK)
    public void requestPhotoSuccess() {
        //成功之后的处理
        //.......
        hasPermission = true;
    }

    @PermissionFail(requestCode = READSDK)
    public void requestPhotoFail() {
        //失败之后的处理，我一般是跳到设置界面
        hasPermission = false;

        boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        boolean showCallPermission = ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.CALL_PHONE);
        if (showRequestPermission) {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
        }
        if (showCallPermission) {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //TODO:先判断是否登录了，并且注册完成了
            case R.id.money:
                skipOtherActivity(WalletActivity.class, false);
                break;
            //拨打电话
            case R.id.customer:

                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    ToastMake.showToast(getResources().getString(R.string.string70));
                    hasReadPermission(Manifest.permission.CALL_PHONE);

                } else {
                    //TODO:权限申请成功
                    android.app.AlertDialog.Builder builder2 = new android.app.AlertDialog.Builder(MainActivity.this);
                    builder2.setMessage("拨打客服电话01064709095");
                    builder2.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder2.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            //需要后台提供
                            tellPhone("01064709095");
                            dialog.dismiss();
                        }
                    });
                    android.app.AlertDialog dialog = builder2.create();
                    dialog.show();
                }
                break;
            case R.id.setting:

                skipOtherActivity(SettingActivity.class, false);
                break;
            case R.id.fix:

                skipOtherActivity(EquipFixActivity.class, false);
                break;
            case R.id.user:
                //TODO:打开侧滑菜单
                if (mDrawer.isDrawerOpen(GravityCompat.START)) {
                    mDrawer.closeDrawer(GravityCompat.START);
                } else {
                    mDrawer.openDrawer(GravityCompat.START);
                }
                break;
            case R.id.message:
                startActivity(new Intent(MainActivity.this, EmailActivity.class));
                break;
            case R.id.share:
                showShare();
                break;
            case R.id.control:
//                startActivity(new Intent(MainActivity.this, ControlActivty.class));
                break;
            case R.id.first:
                mViewPager.setCurrentItem(0, true);
                curritemPostion = 0;
                CompontApplayCation.postion = (curritemPostion + 1)+"";
                break;
            case R.id.second:
                mViewPager.setCurrentItem(1, true);
                curritemPostion = 1;
                CompontApplayCation.postion = (curritemPostion + 1)+"";
                break;
            case R.id.third:
                mViewPager.setCurrentItem(2, true);
                curritemPostion = 2;
                CompontApplayCation.postion = (curritemPostion + 1)+"";
                break;
            case R.id.four:
                mViewPager.setCurrentItem(3, true);
                curritemPostion = 3;
                CompontApplayCation.postion = (curritemPostion + 1)+"";
                break;
        }
    }


    private void showShare() {
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

        // title标题，微信、QQ和QQ空间等平台使用
//        getString(R.string.string31)
        oks.setTitle("按么AMO");
        // titleUrl QQ和QQ空间跳转链接
//        oks.setTitleUrl("赵航");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("你的好友" + Utils.getString(ContectUtils.NICKNAME) + "邀请你边按摩,边赚钱");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
//        oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
//        oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
        Bitmap bgimg0 = getImageFromAssetsFile("applogo.png");
        oks.setImageData(bgimg0);
        // url仅在微信（包括好友和朋友圈）中使用

        if (!TextUtils.isEmpty(Utils.getString(ContectUtils.PHONESAVE)) && Utils.isPhoneNO(Utils.getString(ContectUtils.PHONESAVE))) {
            oks.setUrl("http://amocmf.yuejiyou.com/single_amo/index/invite?invite_phone=" + Utils.getString(ContectUtils.PHONESAVE));
        }else {
            CompontApplayCation.loginNeedFinsh = true;
            Activity activity = AppManager.getInstance().getActivity(MainActivity.class);
            if (activity!=null){
                AppManager.getInstance().finishActivity(MainActivity.class);
            }
            skipOtherActivity(LoginActivity.class,true);

        }
        //分享成功进行回调
        oks.setCallback(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                ToastMake.showToast("分享成功");
                System.out.println("分享成功");
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                System.out.println("分享错误");
            }

            @Override
            public void onCancel(Platform platform, int i) {
                System.out.println("分享取消");
            }
        });
        // 启动分享GUI
        oks.show(MainActivity.this);
    }

    //DrawerLayout不能全屏滑动的问题
    public void setDrawerLeftEdgeSize(Activity activity, DrawerLayout drawerLayout, float displayWidthPercentage) {
        if (activity == null || drawerLayout == null)
            return;
        try {
            // find ViewDragHelper and set it accessible
            Field leftDraggerField = drawerLayout.getClass().getDeclaredField("mLeftDragger");
            leftDraggerField.setAccessible(true);
            ViewDragHelper leftDragger = (ViewDragHelper) leftDraggerField.get(drawerLayout);
            Field edgeSizeField = leftDragger.getClass().getDeclaredField("mEdgeSize");
            edgeSizeField.setAccessible(true);
            int edgeSize = edgeSizeField.getInt(leftDragger);
            DisplayMetrics dm = new DisplayMetrics();
            activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
            edgeSizeField.setInt(leftDragger, (int) (dm.widthPixels * displayWidthPercentage));
        } catch (Exception e) {
        }
    }

    //TODO:只要版本号不一样就可以升级
    private void UpdataApk() {

        int versionCode = getVersionCode();
        String versionNme = getVersionName();
        if (versionNme.contains(".")) {
            String[] vs_name = versionNme.split("\\.");

            for (int i = 0; i < vs_name.length; i++) {
//                if (!vs_name[i].equals("")) {
//                    if (i == 0) {
//                        vs_name1 = Integer.valueOf(vs_name[0]);
//                    }
//                    if (i == 1) {
//                        vs_name2 = Integer.valueOf(vs_name[1]);
//                    }
//                    if (i == 2) {
//                        vs_name3 = Integer.valueOf(vs_name[2]);
//                    }
//                }
            }

        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpUtils
                        .get()
                        .url(UriContect.VERSION)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {

                            }

                            @Override
                            public void onResponse(String response, int id) {
                                UpDataBeen dataBeen = GsonUtil.parseJsonToBean(response, UpDataBeen.class);
                                if (dataBeen == null) {
                                    return;
                                }
                                if (!TextUtils.equals(dataBeen.getStatus(), "1")) {

                                    return;
                                } else {
                                    String version = dataBeen.getVersion();
                                    final String url = dataBeen.getUrl();
                                    final String title = dataBeen.getTitle();
                                    final String msg = dataBeen.getMsg();


//                                    if (version.contains(".")) {
//                                        String[] sv_name = version.split("\\.");
//
//                                        for (int i = 0; i < sv_name.length; i++) {
//
//                                            if (!sv_name[i].equals("")) {
//                                                if (i == 0) {
//                                                    sv_name1 = Integer.valueOf(sv_name[0]);
//                                                    System.out.println(sv_name1 + "");
//                                                }
//                                                if (i == 1) {
//                                                    sv_name2 = Integer.valueOf(sv_name[1]);
//                                                    System.out.println(sv_name2 + "");
//                                                }
//                                                if (i == 2) {
//                                                    sv_name3 = Integer.valueOf(sv_name[2]);
//                                                    System.out.println(sv_name3 + "");
//                                                }
//                                            }
//                                        }
//                                        if (vs_name1 > sv_name1) {
//                                            runOnUiThread(new Runnable() {
//                                                @Override
//                                                public void run() {
//                                                    showDialog(title, msg, url);
//                                                }
//                                            });
//                                        } else {
//                                            if (vs_name2 > sv_name2) {
//
//                                                runOnUiThread(new Runnable() {
//                                                    @Override
//                                                    public void run() {
//                                                        showDialog(title, msg, url);
//                                                    }
//                                                });
//
//                                            } else {
//
//                                                if (vs_name3 > sv_name3) {
//
//                                                    runOnUiThread(new Runnable() {
//                                                        @Override
//                                                        public void run() {
//                                                            showDialog(title, msg, url);
//                                                        }
//                                                    });
//
//                                                } else {
//
//                                                    showNoUpadata("版本提示", "已经是最新版本了");
//                                                }
//
//                                            }
//                                        }
//                                    }
                                }
                            }
                        });
            }
        }).start();


    }

    private void showNoUpadata(String title, String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle(title);
        builder.setCancelable(false);
        builder.setMessage(message);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    /**
     * 获取软件版本号
     *
     * @return
     */
    private int getVersionCode() {
        int versionCode = 0;
        try {
            // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = MainActivity.this.getPackageManager().getPackageInfo(
                    getPackageName(), 0).versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionCode;
    }


    //TODO:进行版本升级操作

    /**
     * 获取版本名字
     *
     * @return
     */
    private String getVersionName() {
        String versionName = "";
        try {
            // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionName = MainActivity.this.getPackageManager().getPackageInfo(
                    getPackageName(), 0).versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionName;
    }

    //弹出对话框
    private void showDialog(String title, String message, final String url) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle(title);
        builder.setCancelable(false);
        builder.setMessage(message);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                ToastMake.showToast("取消升级");
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                ToastMake.showToast("确定升级");

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //TODO:进行升级
                        downLoadApk(url);
                    }
                }).start();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    private void downLoadApk(String url) {
        OkHttpUtils
                .get()
                .url(url)
                .build()
                .execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), "chezai.apk") {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastMake.showToast(call.toString());
                    }

                    @Override
                    public void onResponse(File response, int id) {
                        if (hasPermission) {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                //判读版本是否在7.0以上
                                //新的启动方法
                                Uri apkUri = FileProvider.getUriForFile(MainActivity.this, getLocalClassName() + ".fileprovider", response);//在AndroidManifest中的android:authorities值
                                Intent install = new Intent(Intent.ACTION_VIEW);
                                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                install.setDataAndType(apkUri, "application/vnd.android.package-archive");
                                startActivity(install);
                            } else {
                                //以前的启动方法
                                // 通过Intent安装APK文件
                                Intent install = new Intent(Intent.ACTION_VIEW);
                                install.setDataAndType(Uri.fromFile(response.getAbsoluteFile()), "application/vnd.android.package-archive");
                                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(install);
                            }

                        } else {
                            ToastMake.showToast("请添加读取内存卡权限才能获得最新的版本");
                        }

                    }


                    @Override
                    public void inProgress(final float progress, long total, int id) {
                        super.inProgress(progress, total, id);
//                        int myProgress = (int) progress;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //TODO:可以自定义进度条
                                //                                ProgressBar progressBar = new ProgressBar(MainActivity.this, null, android.R.attr.progressBarStyleHorizontal);
                                //                                progressBar.setMax(100);
                                //                                progressBar.setProgress(myProgress);

                            }
                        });


                    }
                });

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (mDrawer.isDrawerOpen(GravityCompat.START)) {
                mDrawer.closeDrawer(GravityCompat.START);
                return true;
            }
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastMake.showToast(getResources().getString(R.string.string28));
                exitTime = System.currentTimeMillis();
            } else {
                AppManager.getInstance().appExit();
                finish();
            }
            return true;
        }
        return true;
    }

    private void tellPhone(String s) {
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            ToastMake.showToast("拨打电话需要授权拨打电话");

            boolean showCallPermission = ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.CALL_PHONE);
            if (showCallPermission) {
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivity(intent);
            }

        } else {
            Intent intent = new Intent(Intent.ACTION_CALL);
            Uri data = Uri.parse("tel:" + s);
            intent.setData(data);
            startActivity(intent);
        }
    }

    //在onResume()方法注册
    private NetBroadcastReceiver netWorkStateReceiver;

    //onPause()方法注销
    @Override
    protected void onPause() {
        super.onPause();

        unregisterReceiver(netWorkStateReceiver);
        netWorkStateReceiver = null;
    }

    /**
     * @param netMobile 监听网络变化的结果
     */
    @Override
    public void onNetChange(int netMobile) {
        //网络改变增加监听
        if (haveNet) {
            if (isConnected()) {
                netbroke.setVisibility(View.INVISIBLE);
                mViewPager.setVisibility(View.VISIBLE);
                chice();
                haveNet = false;
            } else {
                //TODO:原则上应该打开Login界面
                haveNet = true;
                netbroke.setVisibility(View.VISIBLE);
                mViewPager.setVisibility(View.INVISIBLE);
            }
        }
        //这里可以获取到正在连接的哪一种网络
//        inspectNet();
    }

    private boolean inspectNet() {
        this.netMobile = NetUtil.getNetWorkState(MainActivity.this);
        return isNetConnect();
    }

    /**
     * 判断有无网络 。
     *
     * @return true 有网, false 没有网络.
     */
    private boolean isNetConnect() {
        if (netMobile == 1) {
            return true;
        } else if (netMobile == 0) {
            return true;
        } else if (netMobile == -1) {
            return false;

        }
        return false;
    }


    /*
     * 从Assets中读取图片
     */
    private Bitmap getImageFromAssetsFile(String fileName) {
        Bitmap image = null;
        AssetManager am = getResources().getAssets();
        try {
            InputStream is = am.open(fileName);
            image = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return image;

    }
}
